// reflex-detail.js
Page({
  data: {
    detail: {}
  },

  onLoad(options) {
    const id = options.id
    if (id) {
      this.loadDetail(id)
    }
  },

  // 获取详情并映射字段
  loadDetail(id) {
    wx.request({
      url: `http://localhost:8081/reflexZone/reflexOne?id=${id}`,
      method: 'GET',
      success: (res) => {
        const d = res.data || {}
        const { value: positionEnum, text: positionText } = this.normalizePosition(d.position1)
        const detail = {
          id: d.id,
          name: d.name,
          position: positionEnum,
          positionText,
          location: d.location1,
          function: d.function1,
          operation: d.operation,
          images: this.normalizeUrl(this.pickFirst(d.images)),
          videoUrl: this.normalizeUrl(this.pickFirst(d.shipin)),
          isFree: d.isFree === 1,
          price: d.price || 0
        }
        this.setData({ detail })
      },
      fail: (err) => {
        console.error('获取反射区详情失败:', err)
        wx.showToast({ title: '获取详情失败', icon: 'none' })
      }
    })
  },

  onVideoError(e) {
    console.error('视频播放错误:', e.detail)
    const url = this.data.detail.videoUrl || ''
    // 如果是 https 失败，尝试自动回退到 http 一次
    if (url.startsWith('https://')) {
      const fallback = 'http://' + url.slice(8)
      this.setData({ 'detail.videoUrl': fallback })
      return
    }
    wx.showToast({ title: '视频加载失败', icon: 'none' })
  },

  goBack() {
    if (getCurrentPages().length > 1) {
      wx.navigateBack()
    } else {
      wx.switchTab({ url: '/pages/reflex/reflex' })
    }
  },


  // 规范化URL：可按需升级为 https；当前默认不强制升级以兼容开发环境
  normalizeUrl(url) {
    if (!url) return ''
    // 如需强制升级为 https，将下行改为 true
    const FORCE_HTTPS = false
    if (FORCE_HTTPS && url.startsWith('http://')) return 'https://' + url.slice(7)
    return url
  }
  ,
  // 规范化位置字段：兼容英文枚举与中文值
  normalizePosition(value) {
    const v = (value || '').toString().trim().toLowerCase()
    if (v === 'hand' || value === '手部') return { value: 'hand', text: '手部' }
    if (v === 'foot' || value === '足部') return { value: 'foot', text: '足部' }
    if (v === 'ear' || value === '耳部') return { value: 'ear', text: '耳部' }
    return { value: 'other', text: '其他' }
  }
  ,
  // 逗号分隔时取第一项
  pickFirst(value) {
    if (!value) return ''
    const str = value.toString().trim()
    const first = str.split(',')[0].trim()
    return first
  }
})


